import type { ProxyOptions } from "vite";

type ProxyItem = [string, string];

type ProxyList = ProxyItem[];

type ProxyTargetList = Record<string, ProxyOptions>;

/**
 * 创建代理
 * @param list
 */
function createProxy(list: ProxyList = []) {
  const ret: ProxyTargetList = {};
  for (const [prefix, target] of list) {
    ret[prefix] = {
      target: target,
      changeOrigin: true,
      ws: true,
      rewrite: (path) => path.replace(new RegExp(`^${prefix}`), ""),
      bypass(req, res, options: any) {
        const realUrl = options.target + (options.rewrite ? options.rewrite(req.url) : "");
        res.setHeader("A-Real-Url", realUrl);
      },
    };
  }
  return ret;
}

export function getProxyList(config: any) {
  const list: ProxyList = [
    [config.ocpServer, "http://192.168.30.108:18080"],
    [config.voucherServer, "http://192.168.1.203:1024/prod-api-project/pay-config-server/"],
  ]; //192.168.30.108:18080  192.168.1.33:30414
  return createProxy(list);
}
